﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.CrmContacto.Code;
using CrmContacto.Contracts;
using CrmContacto.Contracts.Contracts.Search;
using Web.Framework;
using CrmContacto.WebApp.Code.InnerClasses;
using Web.Framework.Translate;
using CrmContacto.Contracts.Contracts.Localization;
using Web.CrmContacto.Code.Security;
using Web.Framework.Helpers;

namespace CrmContacto.WebApp.App
{
    public partial class LenguajeEdit : BasePage
    {
        public Lenguaje lenguajeCurrent
        {
            get
            {
                return (Lenguaje)ViewState["lenguajeCurrent"];
            }
            set
            {
                ViewState["lenguajeCurrent"] = value;
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        //LinkButton eliminarButton = new LinkButton();

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            LinkButton guardarButton = new LinkButton();
            guardarButton.ID = "BoCommandGuardar";
            guardarButton.Text = LocalizationProvider.Instance["Bo.Command.Guardar"];
            guardarButton.Click += new EventHandler(lnkGuardar_Click);
            actionButtons.Add(guardarButton);

            LinkButton volverButton = new LinkButton();
            SetJavascriptForClientClickDirtyChech(volverButton);
            volverButton.CausesValidation = false;
            volverButton.ID = "BoCommandVolver";
            volverButton.Text = LocalizationProvider.Instance["Bo.Command.Volver"];
            volverButton.Click += new EventHandler(lnkCancelar_Click);
            actionButtons.Add(volverButton);

            //eliminarButton.ID = "BoCommandEliminar";
            //eliminarButton.CausesValidation = false;
            //eliminarButton.Text = LocalizationProvider.Instance["Bo.Command.Eliminar"];
            //eliminarButton.Click += new EventHandler(eliminarButton_Click);
            //actionButtons.Add(eliminarButton);

            base.LoadContextActions(actionButtons);
        }

        private void eliminarButton_Click(object sender, EventArgs e)
        {
            try
            {
                WebServiceHelper.EliminarLenguaje(lenguajeCurrent.Id);
                NuevoLenguaje();
                Bind();
                this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Message.RegistroEliminado"], WebMessageType.Notification);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {            
            try
            {
                HasPermissionToSeeMe(CrmSecurity.LANGUAJE_MANAGE);
                if (!this.IsPostBack)
                {
                    if (this.Request.QueryString["Id"] == null)
                    {
                        NuevoLenguaje();
                    }
                    else
                    {
                        lenguajeCurrent = WebServiceHelper.ObtenerLenguajeById(this.Request.QueryString["Id"]);
                    }

                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void NuevoLenguaje()
        {
            lenguajeCurrent = new Lenguaje();
        }

        protected override void ApplySecurity()
        {
            base.ApplySecurity();

            //if (!String.IsNullOrEmpty(lenguajeCurrent.Id))
            //{
            //    SetJavascriptForDeleteRecord(eliminarButton, lenguajeCurrent.Nombre);
            //}

            //eliminarButton.Visible = !String.IsNullOrEmpty(lenguajeCurrent.Id);
            //this.lnkGuardar.Visible = HasPermissionFor(PlanProdSecurity.CAUSADESVIO_EDITAR);
        }

        private void Bind()
        {
            if (!String.IsNullOrEmpty(lenguajeCurrent.Id))
            {
                this.txtId.ReadOnly = true;
                this.txtId.CssClass += " readonly";

                this.txtId.Text = lenguajeCurrent.Id;
                this.txtNombre.Text = lenguajeCurrent.Nombre;

                BindGrid();
            }
        }

        private void BindGrid()
        {
            this.Grid.DataSource = this.lenguajeCurrent.PalabraClaveList;
            this.Grid.DataBind();
        }

        private void SetData()
        {
            lenguajeCurrent.Id = this.txtId.Text;
            lenguajeCurrent.Nombre = this.txtNombre.Text;
        }

        private void Save()
        {
            // Seteo las traducciones de los terminos

            //txtTraduccionId_<%# Eval("ClaveId")%>

            foreach (var palabraClave in lenguajeCurrent.PalabraClaveList)
            {
                string inputName = "txtTraduccionId_" + palabraClave.ClaveId;
                string valorTraduccion = this.Request.Form[inputName];
                if (palabraClave.Traduccion != valorTraduccion)
                {
                    palabraClave.Traduccion = valorTraduccion;
                }
            }

            lenguajeCurrent = WebServiceHelper.SaveLenguaje(lenguajeCurrent);
        }

        private void Validar()
        {
            // TODO
        }

        protected void lnkGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                Validar();
                SetData();
                Save();
                Bind();               
                this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Messages.MensajeSaveExitoso"], WebMessageType.Notification);                
               // Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlLenguajeList + "?saveOk=1", true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkCancelar_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlLenguajeList, true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                // Bindear la traducción
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    //PalabraClave palabraClave = (PalabraClave)e.Row.DataItem;
                    //TextBox txtTraduccion = (TextBox)e.Row.FindControl("txtTraduccion");
                    //if (txtTraduccion != null)
                    //{
                    //    txtTraduccion.Text = palabraClave.Traduccion;
                    //}
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {                
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                this.Grid.PageIndex = e.NewPageIndex;

                BindGrid();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkExportarAExcel_Click(object sender, EventArgs e)
        {
            try
            {
                bool previousAllowPaging = this.Grid.AllowPaging;
                this.Grid.AllowPaging = false;

                BindGrid();

                GridViewExportExcelUtil.Export("Lenguajes.xls", this.Grid);

                this.Grid.AllowPaging = previousAllowPaging;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}